package project.messagestack.network;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

import project.messagestack.utils.Logger;

public class NetworkManager implements INetworkManager, Runnable {
  private NetworkManager() {
    try {
      mReadSelector = Selector.open();
    } catch (IOException e) {
      Logger.logError("Error opening selector");
    }
  }
  
  public NetworkManager getInstance() {
    if (mNMInstance == null) {
      mNMInstance = new NetworkManager();
    }
    return mNMInstance;
  }
  
  public void addSocket(SocketChannel socket, Object attachment) {
    try {
      socket.configureBlocking(false);
      socket.register(mReadSelector,
                      SelectionKey.OP_READ | SelectionKey.OP_CONNECT,
                      attachment);
    } catch (ClosedChannelException e) {
      Logger.logError("Error while registering socket " + e.getMessage());
    } catch (IOException e) {
      Logger.logError("Error while configuring socket");
    }
  }
  
  public void run() {
    while (true) {
      
    }
  }
  
  private static NetworkManager mNMInstance;
  private Selector mReadSelector;
}
